<template>
  <view class="profile-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 顶部栏 -->
    <view class="top-bar">
      <text class="title">个人中心</text>
      <button class="logout" @click="logout">退出登录</button>
    </view>

    <!-- 用户信息 -->
    <view class="user-card">
      <view class="avatar">
        <image v-if="user.avatar" :src="user.avatar" class="avatar-img" mode="aspectFill" @error="onAvatarError" />
        <text v-else class="avatar-fallback">{{ user.nameInitial }}</text>
      </view>
      <view class="meta">
        <text class="name">{{ user.displayName }}</text>
        <text class="desc">{{ user.roleText }}</text>
      </view>
    </view>

    <!-- 订单快捷入口 -->
    <view class="order-shortcuts">
      <view class="shortcut" @click="goOrders('all')">
        <text class="shortcut-icon">📋</text>
        <text class="shortcut-label">全部订单</text>
      </view>
      <view class="shortcut" @click="goOrders('groupbuying')">
        <text class="shortcut-icon">👥</text>
        <text class="shortcut-label">拼单中</text>
      </view>
      <view class="shortcut" @click="goOrders('shipping')">
        <text class="shortcut-icon">🚚</text>
        <text class="shortcut-label">待收货</text>
      </view>
      <view class="shortcut" @click="goOrders('refund')">
        <text class="shortcut-icon">💰</text>
        <text class="shortcut-label">退款售后</text>
      </view>
    </view>
    
    <!-- 商家入口（仅商家用户显示） -->
    <view class="merchant-entry" v-if="isMerchant" @click="switchToMerchant">
      <view class="merchant-badge">
        <text class="merchant-icon">🏪</text>
        <text class="merchant-text">切换到商家端</text>
      </view>
      <text class="merchant-arrow">></text>
    </view>
    
    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-item" @click="goEditProfile">
        <view class="menu-icon">✏️</view>
        <text class="menu-text">编辑资料</text>
        <text class="menu-arrow">></text>
      </view>
      <view class="menu-item" @click="goAddress">
        <view class="menu-icon">📍</view>
        <text class="menu-text">地址管理</text>
        <text class="menu-arrow">></text>
      </view>
    </view>
    
    <!-- 账号安全菜单 -->
    <view class="menu-section">
      <view class="section-title">账号安全</view>
      <view class="menu-item" @click="goChangePassword">
        <view class="menu-icon">🔐</view>
        <text class="menu-text">修改密码</text>
        <text class="menu-arrow">></text>
      </view>
      <view class="menu-item" @click="goChangeEmail">
        <view class="menu-icon">📧</view>
        <text class="menu-text">修改邮箱</text>
        <text class="menu-arrow">></text>
      </view>
    </view>
  </view>
  
  <!-- 底部导航栏 -->
  <view class="bottom-nav">
    <view class="nav-item" @click="goHome">
      <text class="nav-icon">🏠</text>
      <text class="nav-label">首页</text>
    </view>
    <view class="nav-item" @click="goGroupBuying">
      <text class="nav-icon">👥</text>
      <text class="nav-label">拼单</text>
    </view>
    <view class="nav-item" @click="goOrders('all')">
      <text class="nav-icon">📦</text>
      <text class="nav-label">订单</text>
    </view>
    <view class="nav-item active" @click="goProfileSelf">
      <text class="nav-icon">👤</text>
      <text class="nav-label">我的</text>
    </view>
  </view>
</template>

<script>
import authService from '../../services/auth.js'

export default {
  data() {
    return {
      statusBarHeight: 0,
      user: {
        displayName: '加载中...',
        roleText: '欢迎回来',
        avatar: '',
        nameInitial: 'U'
      },
      isMerchant: false
    }
  },
  onLoad() {
    this.getStatusBarHeight()
    this.loadUserInfo()
  },
  
  onShow() {
    this.getStatusBarHeight()
    this.loadUserInfo() // 每次显示时刷新用户信息
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },
    
    // 加载用户信息
    async loadUserInfo() {
      try {
        // 先从本地存储获取基本信息（快速显示）
        const localUserInfo = authService.getLocalUserInfo()
        if (localUserInfo) {
          this.updateUserDisplay(localUserInfo)
        }
        
        // 然后从后端获取最新信息
        const response = await authService.getProfile()
        if (response && response.data) {
          this.updateUserDisplay(response.data)
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
        // 如果后端请求失败，使用本地存储的信息
        const localUserInfo = authService.getLocalUserInfo()
        if (localUserInfo) {
          this.updateUserDisplay(localUserInfo)
        }
      }
    },
    
    // 更新用户显示信息
    updateUserDisplay(userInfo) {
      // 显示名称：优先真实姓名，其次用户名
      this.user.displayName = userInfo.realName || userInfo.username || '用户'
      
      // 头像
      this.user.avatar = userInfo.avatar || ''
      
      // 名字首字母（用于头像占位符）
      const name = userInfo.realName || userInfo.username || 'U'
      this.user.nameInitial = name.charAt(0).toUpperCase()
      
      // 角色信息
      this.isMerchant = userInfo.role === 'merchant'
      this.user.roleText = this.isMerchant ? '商家用户' : '欢迎回来'
    },
    
    // 切换到商家端
    switchToMerchant() {
      uni.showModal({
        title: '切换到商家端',
        content: '即将进入商家管理系统',
        success: (res) => {
          if (res.confirm) {
            uni.reLaunch({
              url: '/pages/merchant/home/home'
            })
          }
        }
      })
    },
    
    logout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 清除本地存储的用户信息和token
            uni.removeStorageSync('jwt_token')
            uni.removeStorageSync('user_info')
            
            uni.showToast({
              title: '已退出登录',
              icon: 'success'
            })
            
            // 延迟一下跳转，让用户看到提示
            setTimeout(() => {
              uni.reLaunch({ url: '/pages/login/login' })
            }, 500)
          }
        }
      })
    },
    
    onAvatarError() { 
      console.log('头像加载失败')
      this.user.avatar = '' 
    },
    
    // 跳转到编辑资料
    goEditProfile() {
      uni.navigateTo({
        url: '/pages/profile-edit/profile-edit'
      })
    },
    
    goOrders(filter) {
      const base = '/pages/orders/orders'
      if (filter === 'all') {
        uni.navigateTo({ url: base + '?filter=all' })
      } else if (filter === 'shipping') {
        uni.navigateTo({ url: base + '?filter=shipping' })
      } else if (filter === 'refund') {
        uni.navigateTo({ url: base + '?filter=refund' })
      } else if (filter === 'groupbuying') {
        uni.navigateTo({ url: base + '?filter=groupbuying' })
      }
    },
    // 底部导航按钮
    goHome() { uni.redirectTo({ url: '/pages/home/home' }) },
    goGroupBuying() { uni.redirectTo({ url: '/pages/group-buying/group-buying' }) },
    goProfileSelf() { /* 已经在个人中心，不执行跳转 */ return },
    // 其他导航
    goAddress() { uni.navigateTo({ url: '/pages/address/address' }) },
    goChangePassword() { uni.navigateTo({ url: '/pages/auth/change-password' }) },
    goChangeEmail() { uni.navigateTo({ url: '/pages/auth/change-email' }) }
  }
}
</script>

<style lang="scss" scoped>
.profile-container { min-height: 100vh; background: #f5f5f5; }
.status-bar { 
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

.top-bar { 
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  display: flex; 
  align-items: center; 
  justify-content: space-between; 
  padding: 20rpx 30rpx; 
  background: #fff; 
  border-bottom: 1rpx solid #eee;
  z-index: 998;
}
.title { 
  font-size: 32rpx; 
  font-weight: 700; 
  color: #333; 
  flex: 1;
  text-align: center;
}
.logout { 
  height: 64rpx; 
  padding: 0 24rpx; 
  border-radius: 32rpx; 
  background: #ff4757; 
  color: #fff; 
  border: none; 
  font-size: 26rpx;
  position: absolute;
  right: 30rpx;
}

.user-card { 
  display: flex; 
  gap: 20rpx; 
  align-items: center; 
  background: #fff; 
  margin-top: calc(var(--status-bar-height) + 88rpx + 20rpx);
  margin-left: 20rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  padding: 30rpx; 
  border-radius: 16rpx; 
}
.avatar { width: 120rpx; height: 120rpx; border-radius: 50%; background: #ffe0b2; color: #ff8a00; display: flex; align-items: center; justify-content: center; font-size: 48rpx; font-weight: 800; overflow: hidden; }
.avatar-img { width: 100%; height: 100%; }
.avatar-fallback { font-size: 48rpx; font-weight: 800; color: #ff8a00; }
.meta .name { display: block; font-size: 32rpx; font-weight: 700; color: #333; }
.meta .desc { display: block; font-size: 24rpx; color: #999; margin-top: 6rpx; }

.order-shortcuts { 
  background: #fff; 
  margin: 20rpx; 
  padding: 30rpx 20rpx; 
  border-radius: 16rpx; 
  display: flex; 
  justify-content: space-around;
  gap: 12rpx;
}

.shortcut { 
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 6rpx;
  padding: 16rpx 8rpx;
  border-radius: 12rpx;
  border: 2rpx solid #ffe0b2;
  background: linear-gradient(135deg, #fff7ec 0%, #fffaf0 100%);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
    background: linear-gradient(135deg, #ffe0b2 0%, #ffd699 100%);
  }
  
  .shortcut-icon {
    font-size: 32rpx;
    transition: transform 0.3s ease;
  }
  
  .shortcut-label {
    font-size: 20rpx;
    color: #ff8a00;
    font-weight: 600;
    text-align: center;
  }
  
  &:active .shortcut-icon {
    transform: scale(1.08);
  }
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 120rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
  
  .nav-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    padding: 12rpx 0;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    
    &:active {
      transform: scale(0.95);
    }
    
    .nav-icon {
      font-size: 44rpx;
      transition: all 0.3s ease;
      filter: grayscale(100%);
      opacity: 0.6;
    }
    
    .nav-label {
      font-size: 22rpx;
      color: #999;
      font-weight: 500;
      transition: all 0.3s ease;
    }
    
    /* 选中状态 */
    &.active {
      .nav-icon {
        filter: grayscale(0%);
        opacity: 1;
        transform: scale(1.1);
      }
      
      .nav-label {
        color: #667eea;
        font-weight: 600;
      }
      
      /* 选中指示器 */
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 6rpx;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 3rpx;
      }
    }
  }
}



/* 功能菜单 */
.menu-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
  
  .section-title {
    padding: 24rpx 30rpx 12rpx;
    font-size: 24rpx;
    color: #999;
    font-weight: 600;
  }
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;
  transition: background 0.3s ease;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background: #f8f8f8;
  }
  
  .menu-icon {
    font-size: 32rpx;
    margin-right: 20rpx;
  }
  
  .menu-text {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
  
  .menu-arrow {
    font-size: 24rpx;
    color: #999;
  }
}

/* 商家入口 */
.merchant-entry {
  background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 8rpx 20rpx rgba(255, 138, 0, 0.3);
  cursor: pointer;
  transition: transform 0.3s ease;
  
  &:active {
    transform: scale(0.98);
  }
}

.merchant-badge {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.merchant-icon {
  font-size: 36rpx;
}

.merchant-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #fff;
}

.merchant-arrow {
  font-size: 28rpx;
  color: #fff;
  font-weight: 700;
}
</style>
